package com.adinall.dsp.core.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

/**
 * 多线程工具类
 * 
 * @author 高万超
 * @version V1.0.0 $ 2017年7月14日 上午10:58:39
 */
public final class ThreadUtils {

    public static ExecutorService newFixedThreadPool(int size, final String threadNamePrefix) {

        return Executors.newFixedThreadPool(size, new ThreadFactory() {

            int threadIdx = 0;

            public Thread newThread(Runnable r) {
                return new Thread(r, threadNamePrefix + threadIdx++);
            }
        });
    }

    public static void execute(List<? extends Callable> taskList, final String taskName) throws Exception {

        List<Future> futureList = new ArrayList();

        ExecutorService pool = newFixedThreadPool(taskList.size(), taskName);

        for (Callable callable : taskList) {
            futureList.add(pool.submit(callable));
        }
        pool.shutdown();

        for (Future f : futureList) {
            f.get();
        }
    }

    public static <T> List<T> submit(List<? extends Callable<T>> taskList, final String taskName) throws Exception {

        List<Future<T>> futureList = new ArrayList();

        ExecutorService pool = newFixedThreadPool(taskList.size(), taskName);

        for (Callable<T> callable : taskList) {
            futureList.add(pool.submit(callable));
        }
        pool.shutdown();

        List<T> data = new ArrayList<>();

        for (Future<T> f : futureList) {
            data.add(f.get());
        }

        return data;
    }
}